/**
 * $Id: DealOverDateDataMgr.java,v 1.1 2006/06/21 11:39:38 star Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner.datadeal;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.SQLConst;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.runner.smscommand.SubmitCmd;
import com.haoxi.gateway.util.db.DBConnectUtil;
import com.haoxi.gateway.util.db.DealOracleDBUtil;

/**
 * 用于加载那些在网关系统崩溃时持久化到Mysql表中的数据到相应的内存中
 * 
 * Revision History
 * 
 * 2006-5-31,star.Zhao,created it
 */
/**
 * TODO
 * 
 * Revision History
 * 
 * 2006-6-21,star.Zhao,created it
 */
public class DealOverDateDataMgr {
    private final static Log log = LogFactory.getLog(DealOverDateDataMgr.class);
    public final static String OVERDATE_ERROR_INFO = "No_MTResp";
    private final static String MY_NAME = "DealOverDataMgr";

    /**
     * 单例模式
     */
    private static DealOverDateDataMgr instance = new DealOverDateDataMgr();
    private DealOverDateDataMgr() {}
    public static DealOverDateDataMgr getInstance() {
        return DealOverDateDataMgr.instance;
    }

    /**
     * 系统初始化，对相应的超时数据的处理
     * 
     * @return
     */
    public boolean initSystemDeal() {
        boolean bOK = false;
        Map map = RunnerMgr.getInstance().getSystemConf();
        String gateway_DBName = (String) map.get(SYSConst.CONF_DB_MYSQL);
        String gateway_sms = (String) map.get(SYSConst.CONF_DB_GATEWAY);
        
        List list = getOverDateSendedMTList(gateway_DBName);
        int count = list.size();
        if (count > 0) {
            int[] res = DealOracleDBUtil.saveBatchMsgHistory(MY_NAME, list,
                    gateway_sms);
            if (res.length == count) {
                if (count == clearAllOverDateData(gateway_DBName)) {
                    log
                            .debug("DealOverDataMgr.initSystemDeal() deal Overdate Data successfully!---");
                    bOK = true;
                } else {
                    log
                            .debug("DealOverDataMgr.initSystemDeal() deal Overdate Data unsuccessfully! Beacuse of clearAllOverDateData(). ---");
                    bOK = false;
                }
            } else {
                log
                        .debug("DealOverDataMgr.initSystemDeal() deal Overdate Data unsuccessfully! Beacuse of saveBatchMsgHistory(). ---");
                bOK = false;
            }
        } else {
            // 没有超时数据，成功
            bOK = true;
        }
        return bOK;
    }

    /**
     * 获得已经超时的需要report的MT数据
     * 
     * @return
     */
    private List getOverDateSendedMTList(String dbName) {
        List result = new ArrayList();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBConnectUtil.open(dbName);

            // 加统计count(*)
            ps = conn.prepareStatement(SQLConst.SELECT_SENDED_MT);
            rs = ps.executeQuery();

            SubmitCmd submitCmd = null;
            while (rs.next()) {
                submitCmd = new SubmitCmd();
                submitCmd.setSequence(rs.getString("SEQUENCEID"));
                submitCmd.setStype(rs.getInt("STYPE"));
                submitCmd.setServiceId(rs.getString("SERVICE_ID"));
                submitCmd.setOrgMobile(rs.getString("ORGMOBILE"));
                submitCmd.setOrgMobileType(rs.getInt("ORGMOBILETYPE"));
                submitCmd.setDestMobile(rs.getString("DEDESTMOBILE"));
                submitCmd.setDestMobileType(rs.getInt("DESTMOBILETYPE"));
                submitCmd.setFeeMobile(rs.getString("FEEMOBILE"));
                submitCmd.setFeeMobileType(rs.getInt("FEEMOBILETYPE"));
                submitCmd.setFeeType(rs.getString("FEETYPE"));
                submitCmd.setFeeCode(rs.getInt("FEECODE"));
                submitCmd.setMsgContent(rs.getString("CONTENT"));
                submitCmd.setProvice(rs.getInt("PROVINCE"));
                submitCmd.setCity(rs.getInt("CITYNUMBER"));
                submitCmd.setCityName(rs.getString("CITYNAME"));
                submitCmd.setLinkID(rs.getString("RESERVED"));
                submitCmd.setCp(rs.getInt("CP"));
                submitCmd.setSubmitTime(rs.getString("SUBMITTIME"));
                submitCmd.setSid(rs.getString("SID"));
                submitCmd.setGateWayCode(rs.getString("GATEWAYCODE"));
                submitCmd.setMomtRelateID(rs.getString("MOMT_ID"));
                submitCmd.setSubmitStatus(DealOverDateDataMgr.OVERDATE_ERROR_INFO);
                result.add(submitCmd);
            }
        } catch (SQLException sqle) {
            log
                    .error("SQLException in InitMemoryData.getSendedMTList()!",
                            sqle);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log
                        .error(
                                "release db connection unsuccessfully in InitMemoryData.getSendedMTList()!",
                                sqle);
            }
        }

        return result;
    }

    /**
     * 清除所有的超时数据
     * 
     * @param dbName
     * @return
     */
    private int clearAllOverDateData(String dbName) {
        int result = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = DBConnectUtil.open(dbName);

            // 加统计
            ps = conn.prepareStatement(SQLConst.DELETE_OVERDATE_SENDED_MT);
            result = ps.executeUpdate();
        } catch (SQLException sqle) {
            log
                    .error("SQLException in InitMemoryData.getSendedMTList()!",
                            sqle);
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log
                        .error(
                                "release db connection unsuccessfully in InitMemoryData.getSendedMTList()!",
                                sqle);
            }
        }
        return result;
    }
}
